<template>
  <div class="user-info-drawer">
    <div class="handle">
      <div class="avatar">
        <img :src="userInfo.url" alt="avatar" />
      </div>
      <div class="info">
        <span>{{ userInfo.username }}</span>
        <span>{{ userType }}</span>
      </div>
      <div class="logout" @click="logout">退出登录</div>
    </div>
    <!-- 详细信息 -->
    <div class="detail-form">
      <div v-if="!showPasswordForm" class="detail">
        <div class="detail-item">
          <span>电话</span>
          <el-input
            :readonly="isForbid"
            v-model="userInfo.phone"
            :placeholder="userInfo.phone || '暂无数据'"
          ></el-input>
        </div>
        <div class="detail-item">
          <span>邮箱</span>
          <el-input
            :readonly="isForbid"
            v-model="userInfo.email"
            :placeholder="userInfo.email || '暂无数据'"
          ></el-input>
        </div>
        <div class="detail-item">
          <span>地址</span>
          <el-input
            :autosize="{ minRows: 1, maxRows: 4 }"
            type="textarea"
            :readonly="isForbid"
            v-model="userInfo.motto"
            :placeholder="userInfo.motto || '暂无数据'"
          ></el-input>
        </div>
        <div class="detail-item">
          <span>职业</span>
          <el-input
            :readonly="isForbid"
            v-model="userInfo.job"
            :placeholder="userInfo.job || '暂无数据'"
          ></el-input>
        </div>
        <div class="detail-item">
          <span>生日</span>
          <el-input
            :readonly="isForbid"
            v-model="userInfo.birthday"
            :placeholder="userInfo.birthday || '暂无数据'"
          ></el-input>
        </div>
        <div class="detail-item">
          <span>签名</span>
          <el-input
            :autosize="{ minRows: 1, maxRows: 4 }"
            type="textarea"
            v-model="userInfo.signature"
            :placeholder="userInfo.signature || '这个人很懒什么都没留下'"
          ></el-input>
        </div>
        <div class="btns" v-if="!isForbid">
          <el-button type="text" @click="showPasswordForm = true"
            >修改密码</el-button
          >
          <el-button type="text" @click="handleUpload">上传头像</el-button>
          <el-button type="text" @click="handleSave">保存</el-button>
        </div>
      </div>
      <!-- 密码修改框 -->
      <div v-else class="detail">
        <el-form
          ref="passwordEditForm"
          :model="passwordForm"
          label-width="80px"
          :rules="rules"
        >
          <el-form-item label="旧密码" prop="oldPassword">
            <el-input
              type="password"
              show-password
              v-model="passwordForm.oldPassword"
              placeholder="请输入旧密码"
            ></el-input>
          </el-form-item>
          <el-form-item label="新密码" prop="newPassword">
            <el-input
              type="password"
              show-password
              v-model="passwordForm.newPassword"
              placeholder="请输入新密码"
            ></el-input>
          </el-form-item>
          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input
              type="password"
              show-password
              v-model="passwordForm.confirmPassword"
              placeholder="请再次输入新密码"
            ></el-input>
          </el-form-item>
        </el-form>
        <el-button type="text" @click="submitForm">提交</el-button>
      </div>
      <el-button type="text" @click="handleForbid">{{
        isForbid ? '修改' : '取消'
      }}</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue';
import { userData } from '../stores/userData.js';
import { storeToRefs } from 'pinia';
import { ElMessage } from 'element-plus';
import axios from 'axios';
const { user } = storeToRefs(userData());

import { useRouter } from 'vue-router';
const router = useRouter();
import {
  updateUserInfo,
  uploadAvatar,
  updateUserPassword,
} from '../apis/index.js';

const isForbid = ref(true);

//是否显示修改密码表单
const showPasswordForm = ref(false);

const passwordEditForm = ref(null);

// 密码修改表单
const passwordForm = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: '',
});

//表单校验
const validatePass = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入密码'));
  } else if (!/^[a-zA-Z0-9_]{6,12}$/.test(value)) {
    callback(new Error('密码6-12位，仅允许字母、数字和下划线'));
  } else {
    callback();
  }
};

const validatePass2 = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'));
  } else if (value !== passwordForm.value.confirmPassword) {
    callback(new Error('两次输入密码不一致!'));
  } else {
    callback();
  }
};

//表单规则,先验证不能为空
const rules = {
  oldPassword: [{ required: true, message: '请输入旧密码', trigger: 'change' }],
  newPassword: [{ validator: validatePass, trigger: 'blur' }],
  confirmPassword: [{ validator: validatePass2, trigger: 'blur' }],
};

//提交表单
const submitForm = () => {
  passwordEditForm.value.validate((valid) => {
    if (valid) {
      const { oldPassword, newPassword } = passwordForm.value;
      updateUserPassword({
        ...user.value,
        password: newPassword,
        oldPassword,
      }).then((res) => {
        console.log(res, 'res');
        if (res.data.status === 1) {
          ElMessage.success('修改成功');
          isForbid.value = true;
          showPasswordForm.value = false;
          passwordForm.value = {
            oldPassword: '',
            newPassword: '',
            confirmPassword: '',
          };
          //退出登录
          setTimeout(() => {
            logout();
          }, 1000);
        } else {
          ElMessage.error('修改失败');
        }
      });
    } else {
      ElMessage.error('请检查输入');
    }
  });
};

const userInfo = ref({
  email: '',
  id: '',
  motto: '',
  password: '',
  tel: null,
  type: 'user',
  updatedAt: '',
  url: '',
  username: '游客',
  phone: '',
  job: null,
  birthday: null,
  signature: null,
});

//用属性计算器计算用户类型
const userType = computed(() => {
  if (user.value.type === 'admin') {
    return '管理员';
  } else if (user.value.type === 'user') {
    return '普通用户';
  } else {
    return '交通管理部门';
  }
});

const handleForbid = () => {
  isForbid.value = !isForbid.value;
  if (!isForbid.value) {
    userInfo.value = user.value;
    showPasswordForm.value = false;
    passwordForm.value = {
      oldPassword: '',
      newPassword: '',
      confirmPassword: '',
    };
  } else {
    showPasswordForm.value = false;
  }
};

//保存修改
const handleSave = () => {
  updateUserInfo(userInfo.value).then((res) => {
    if (res.data.status === 1) {
      user.value = userInfo.value;
      isForbid.value = true;
    } else {
      ElMessage.error('修改失败');
    }
  });
};

//上传头像
const handleUpload = () => {
  const input = document.createElement('input');
  input.type = 'file';
  input.accept = 'image/*';
  input.click();
  input.onchange = (e) => {
    handleFileChange(e);
  };
};

function handleFileChange(event) {
  let file = event.target.files[0];
  //获取图片的宽和高
  let img = new Image();
  img.src = URL.createObjectURL(file);
  img.onload = function () {
    let width = img.width;
    let height = img.height;
    if (width / height > 1.1 || width / height < 0.9) {
      ElMessage.error('图片比例不对');
      return;
    }
  };
  //要将file传递到服务端
  // file => formData => axios发送请求(修改content-type)
  // file要发送出去 必须放到formdata
  let formData = new FormData();
  formData.append('file', file);
  formData.append('username', userInfo.value.username);
  formData.append('type', userInfo.value.type);
  uploadAvatar(formData).then((res) => {
    // console.log(res, "res");
    if (res.data.status === 1) {
      userInfo.value.url = res.data.url;
      ElMessage.success('上传成功');
      isForbid.value = true;
      showPasswordForm.value = false;
      passwordForm.value = {
        oldPassword: '',
        newPassword: '',
        confirmPassword: '',
      };
    } else {
      ElMessage.error('上传失败');
    }
  });
}

//退出登录
const logout = () => {
  localStorage.removeItem('jwtToken');
  delete axios.defaults.headers.common['Authorization'];
  router.push('/login');
};

userInfo.value = user.value;
</script>

<style scoped lang="scss">
.user-info-drawer {
  .handle {
    display: flex;
    align-items: center;
    padding: 20px;
    .avatar {
      width: 60px;
      height: 60px;
      border-radius: 50%;
      overflow: hidden;
      border: 2px solid #666;
      img {
        width: 100%;
        height: 100%;
      }
    }
    .info {
      display: flex;
      flex-direction: column;
      gap: 15px;
      margin-left: 15px;
      span:nth-child(2) {
        font-size: 14px;
        color: #666;
      }
    }
    .logout {
      margin-left: auto;
      cursor: pointer;
      color: #666;
      font-size: 14px;
      &:hover {
        color: #f50;
      }
    }
  }
  .detail-form {
    margin-top: 30px;
    padding: 20px;
    display: flex;
    gap: 10px;
    border: 1px solid #eee;
    box-shadow: 1px 1px 5px rgba(0, 0, 0, 0.4);
    .detail {
      flex: 1;
      display: flex;
      flex-direction: column;
      gap: 15px;
      .detail-item {
        display: flex;
        align-items: center;
      }
      .btns {
        display: flex;
        justify-content: flex-end;
      }
      span {
        width: 60px;
      }
      .el-input {
        :deep(.el-input__wrapper) {
          border: none;
          box-shadow: none;
        }
        .el-input__wrapper.is-focus {
          border: none;
          box-shadow: none;
        }
      }
      .el-textarea {
        :deep(.el-textarea__inner) {
          border: none;
          box-shadow: none;
        }
        .el-textarea__inner.is-focus {
          border: none;
          box-shadow: none;
        }
      }
    }
  }
}
</style>
